//
//  MJTUserAccountViewModel.swift
//  swiftWeiBo
//
//  Created by MJT on 16/7/12.
//  Copyright © 2016年 MJT. All rights reserved.
//

import UIKit
// 封装OAuth 登录相关接口
class MJTUserAccountViewModel: NSObject {

    //单例访问点
    static let shareUserAccount: MJTUserAccountViewModel = MJTUserAccountViewModel()

    //获取用户对象在沙盒路径里面解档对象
    var userAccount: MJTUserAccount? {
        return MJTUserAccount.loadUserAccount()
    }
    //构造函数私有化
   private override init() {
        super.init()
    }
    //封装accessToken是否为nil ,表示登录结果
    var isLogin: Bool {
        return accessToken != nil
    }

    //判断过期
    var accessToken: String?{
        //判断accessToken是否为nil
        guard let token = userAccount?.access_token else {
            return nil
        }
        //判断过期时间与当前时间,比较结果是升续,降续,相等
        let result = userAccount?.expiresDate?.compare(NSDate())
        //使用降续表示从大到小
        if result == NSComparisonResult.OrderedDescending {
            return token
        } else {
            return nil
        }
    }

    //通过授权码获取accesstoken
    func requestAccesstoken(code: String,callBack:((isSucess: Bool)->())){
        MJTNetworkTools.sharedTools.requestAccesstoken(code) { (response, error) -> () in
            if error != nil {
                print(error)
                callBack(isSucess: false)
                return
            }
            guard let dic = response as? [String: AnyObject] else {
                print("这不是一个正确的Json格式")
                callBack(isSucess: false)
                return
            }
            let userAccount = MJTUserAccount(dic: dic)
//            print(userAccount)
            self.requestUserInfo(userAccount,callBack: callBack)
        }
    }
    private func requestUserInfo(userAccount: MJTUserAccount,callBack:((isSucess: Bool)->())) {

        MJTNetworkTools.sharedTools.requestUserInfo(userAccount) { (response, error) -> () in
            if error != nil {
                print(error)
                callBack(isSucess: false)
                return
            }
            guard let dic = response as? [String: AnyObject] else {
                print("不是一个正确json格式")
                callBack(isSucess: false)
                return
            }
            //代码到此字典一定有值
            let name = dic["name"]
            let avatar_large = dic["avatar_large"]
            //s设置用户头像用户名
            userAccount.name = name as? String
            userAccount.avatar_large = avatar_large as? String
            //保存用户对象
            let result = userAccount.saveUserAccount()

            if result {
                callBack(isSucess: true)
            } else {
                callBack(isSucess: false)
            }

            print(userAccount)
        }
    }
}
